import axios from "axios";
// 创建axios实例
const ajax = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 10000,
    headers: {
        // 请求格式
        'Content-Type': 'application/json;charset=utf-8',
        // 对应国际化资源文件后缀
        'Content-Language': 'zh_CN'
    }
});

// 请求拦截器
ajax.interceptors.request.use((config: any) => {
    const token = localStorage.getItem('token');
    if (token) {
        config.headers['Authorization'] = token;
    }
    return config;
}, err => {
    return Promise.reject(err);
});

// 响应拦截器
ajax.interceptors.response.use((res: any) => {
    const code = res.data.code || 200;
    // 检查token是否刷新
    if (res.headers['refreshtoken']) {
        // 存入新的token
        localStorage.setItem('token', res.headers['refreshtoken']);
    }
    // 二进制数据则直接返回
    if(res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer'){
        return res.data
    }
    if (code === 401) {
        try {
            window.$dialog.warning({
                title: '警告',
                content: `${res.data.message}。是否重新登陆？`,
                positiveText: '确定',
                negativeText: '取消',
                onPositiveClick: () => {
                    localStorage.clear()
                    location.href = '/login';
                },
            });
        } catch (e) {
            localStorage.clear()
            location.href = '/';
        }
    } else if (code != 200) {
        window.$notification.error({
            content: '提示',
            meta: res.data.message,
            duration: 2000,
        });
    }
    return Promise.resolve(res?.data);
}, err => {
    let { message } = err;
    if (message == "Network Error") {
        message = "服务器连接异常";
    }
    else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        if (err.response.data.message) {
            message = err.response.data.message;
        } else {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
    }
    try {
        window.$notification.error({
            content: '错误',
            meta: message,
            duration: 2000,
        });
    } catch (e) {
        localStorage.clear()
    }
    return Promise.reject(err);
});

export default ajax;
